package com.sixstones.fragment.web.fragment;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sixstones.fragment.entity.CatagoryEntity;
import com.sixstones.fragment.entity.FragmentEntity;
import com.sixstones.fragment.enums.ResultEnum;
import com.sixstones.fragment.service.CatagoryService;
import com.sixstones.fragment.service.FragmentService;
import com.sixstones.fragment.vo.CatagoryInfo;
import com.sixstones.fragment.vo.FragmentResult;

@Controller
@RequestMapping(value = "/fragment")
public class FragmentController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private FragmentService service;
	
	@Autowired
	private CatagoryService catagoryService;

	@RequestMapping("/toAdd/{catagoryId}")
	public String toAddFragment(@PathVariable(value = "catagoryId") int catagoryId, Model model) {
		CatagoryInfo info = catagoryService.getCatagoryInfo(catagoryId,false);
		model.addAttribute("catagoryInfo", info);
		return "fragment.add";
	}

	@RequestMapping(value = "/getContent", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public FragmentResult getFragmentContent(int fragmentId) {
		FragmentResult result = new FragmentResult(ResultEnum.SUCCESS, true);
		result.setData(service.getFragmentContent(fragmentId));
		return result;

	}

	@RequestMapping(value = "/add", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public FragmentResult addFragment(String title, String content, int catagoryId) {
		try {
			FragmentEntity fragment = new FragmentEntity();
			fragment.setTitle(title);
			fragment.setContent(content);
			fragment.setCatagoryId(catagoryId);
			service.addNewFragment(fragment);
			return new FragmentResult(ResultEnum.SUCCESS, true);
		} catch (Exception e) {
			logger.error("新增碎片异常,{}", e);
			return new FragmentResult(ResultEnum.FAIL, false);
		}
	}
}
